<template>
  <view class="chat-container" @tap="closeEmojiPanel">
    <view class="chat-content">
      <scroll-view
        class="message-list"
        scroll-y="true"
        :scroll-top="scrollTop"
        :scroll-into-view="scrollToMessageId"
        :scroll-with-animation="false"
        @scrolltoupper="onScrollToUpper"
        @scrolltolower="onScrollToLower"
      >
        <view class="message-wrapper">
          <view class="safe-area"></view>
          <view
            v-for="(message, index) in chatMessages"
            :key="index"
            :id="'msg-' + index"
            class="message-item"
            :class="{ 'message-mine': isMineMessage(message) }"
          >
            <view class="avatar">
              <image
                :src="
                  isMineMessage(message)
                    ? getImageUrl(currentUserInfo.avatar)
                    : getImageUrl(chatUser.avatar)
                "
                mode="aspectFill"
              ></image>
            </view>
            <view class="message-content">
              <view class="message-bubble">
                <template v-if="message.msgType === 1">
                  <image
                    :src="getImageUrl(message.message)"
                    mode="widthFix"
                    class="message-image"
                    @tap="previewImage(getImageUrl(message.message))"
                  ></image>
                </template>
                <template v-else>
                  <text>{{ message.message }}</text>
                </template>
              </view>
              <!-- 隐藏时间 -->
              <!-- <view class="message-time">{{ message.sendTime }}</view> -->
            </view>
          </view>
          <view class="safe-area"></view>
        </view>
      </scroll-view>

      <view class="msg-input-container">
        <view class="msg-input-wrapper">
          <view class="emoji-btn" @tap.stop="toggleEmojiPanel">😊</view>
          <view class="image-btn" @tap.stop="chooseImage">🖼️</view>
          <input
            type="text"
            v-model="inputMessage"
            class="msg-input"
            placeholder="请输入消息"
          />
          <button class="send-btn" @tap.stop="sendMessage">发送</button>
        </view>
        <!-- 表情面板 -->
        <view class="emoji-panel" v-if="showEmojiPanel" @tap.stop>
          <scroll-view scroll-y class="emoji-list">
            <view class="emoji-grid">
              <view
                class="emoji-item"
                v-for="(emoji, index) in emojiList"
                :key="index"
                @tap="selectEmoji(emoji)"
              >
                {{ emoji }}
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
    <view v-if="showPreview" class="image-preview" @tap="closePreview">
      <image
        :src="previewImageUrl"
        mode="aspectFit"
        class="preview-image"
      ></image>
    </view>
  </view>
</template>

<script setup>
import { ref, defineProps, nextTick, watch, onMounted } from "vue";
import {
  GetMessage,
  SendMessage,
  UploadMessageFile,
} from "@/http/apis/chat/chat";
import { onLoad } from "@dcloudio/uni-app";
import { signalR } from "@/utils/signalr.js";

// 定义 props 来接收 userId
const props = defineProps({
  userId: {
    type: String,
    required: true,
  },
});

// 当前选择的聊天用户信息pinia
import { CurrentChatUserInfoStore } from "@/store/currentChatUserInfo";
const currentChatUserInfoStore = CurrentChatUserInfoStore();

// 当前登录用户信息pinia
import { UserInfoStore } from "@/store/userInfo.js";
const userInfoStore = UserInfoStore();

// 当前用户信息
const currentUserInfo = ref({});

// 聊天用户信息
const chatUser = ref({});

// 聊天消息列表
const chatMessages = ref([]);

const inputMessage = ref("");
const scrollTop = ref(0);

// 添加滚动到消息ID的ref
const scrollToMessageId = ref("");

// 表情相关
const showEmojiPanel = ref(false);
const emojiList = ref([]);

// 预览相关
const showPreview = ref(false);
const previewImageUrl = ref("");

// 判断是否是自己发送的消息
const isMineMessage = (message) => {
  return message.sendUserId === currentUserInfo.value.id;
};

/**
 * 获取查询字符串
 *
 * @param options 查询选项
 * @returns 无返回值
 */
const getQueryStringAndGetUserInfo = (options) => {
  if (!options) return;
  console.log("Options:", options);

  // 获取当前chat用户信息
  const chatUserInfo = currentChatUserInfoStore.currentChatUserInfo;
  if (!chatUserInfo || chatUserInfo.userId != options) return;
  chatUser.value = chatUserInfo;
  console.log("Chat user:", chatUser.value);

  // 获取当前用户信息
  const userInfo = userInfoStore.getUserInfo;
  currentUserInfo.value = userInfo;
  console.log("Current user info:", currentUserInfo.value);
};

// 滚动到最后一条消息
const scrollToBottom = () => {
  nextTick(() => {
    const query = uni.createSelectorQuery();
    query
      .select(".message-wrapper")
      .boundingClientRect((data) => {
        if (data) {
          scrollTop.value = data.height;
        }
      })
      .exec();
  });
};

// 获取聊天消息
const getChatMessages = async () => {
  const res = await GetMessage(chatUser.value.userId);
  if (res.result) {
    // 确保消息按时间排序
    chatMessages.value = res.result.sort(
      (a, b) => new Date(a.sendTime) - new Date(b.sendTime)
    );
    // 滚动到最新消息
    scrollToBottom();
  }
};

const getMessage = () => {
  signalR.off("ReceiveMessage");
  signalR.on("ReceiveMessage", (data) => {
    console.log("收到消息:", data);
    // 是自己发送的消息
    if (data.sendUserId !== currentUserInfo.value.id) {
      chatMessages.value.push(data);
      scrollToBottom();
    }
  });
};

// 监听消息列表变化
watch(
  () => chatMessages.value.length,
  () => {
    scrollToBottom();
  }
);

// 滚动到顶部时的处理函数
const onScrollToUpper = () => {
  console.log("滚动到顶部");
  // 这里可以添加加载历史消息的逻辑
};

// 滚动到底部时的处理函数
const onScrollToLower = () => {
  console.log("滚动到底部");
};

onMounted(() => {
  scrollToBottom();
  getMessage();
  loadEmojis();
});

const sendMessage = async () => {
  if (!inputMessage.value.trim()) return;
  // TODO: 实现发送消息的逻辑

  const newMessage = {
    sendUserId: currentUserInfo.value.id,
    receiveUserId: chatUser.value.userId,
    message: inputMessage.value,
    sendTime: new Date().toLocaleString(),
    title: "",
    msgType: 0,
  };
  chatMessages.value.push(newMessage);
  await SendMessage(newMessage);
  inputMessage.value = "";
  // 关闭表情
  showEmojiPanel.value = false;
};

// 加载表情数据
const loadEmojis = async () => {
  try {
    const emojiData = await uni.request({
      url: "/static/emoji.json",
    });
    if (emojiData.data) {
      emojiList.value = emojiData.data;
    }
  } catch (error) {
    console.error("加载表情失败:", error);
  }
};

// 切换表情面板
const toggleEmojiPanel = () => {
  showEmojiPanel.value = !showEmojiPanel.value;
};

// 选择表情
const selectEmoji = (emoji) => {
  inputMessage.value += emoji;
};

// 关闭表情面板
const closeEmojiPanel = () => {
  showEmojiPanel.value = false;
};

// 预览图片
const previewImage = (url) => {
  previewImageUrl.value = url;
  showPreview.value = true;
};

// 关闭预览
const closePreview = () => {
  showPreview.value = false;
};

// 选择图片
const chooseImage = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1, // 只选择一张图片
      sizeType: ["compressed"], // 压缩图片
      sourceType: ["album", "camera"], // 可以从相册或
    });

    console.log("res", res);

    const filePath = res.tempFiles[0];
    // 上传图片并发送消息
    const uploadRes = await UploadMessageFile(filePath);
    if (uploadRes.type === "success") {
      const newMessage = {
        sendUserId: currentUserInfo.value.id,
        receiveUserId: chatUser.value.userId,
        message: uploadRes.result.url,
        sendTime: new Date().toLocaleString(),
        title: "",
        msgType: 1, // 图片类型
      };
      chatMessages.value.push(newMessage);
      await SendMessage(newMessage);
    }
  } catch (error) {
    console.error("发送图片失败:", error);
  }
};

onLoad(async () => {
  getQueryStringAndGetUserInfo(props.userId);
  await getChatMessages();
});
</script>

<style lang="scss" scoped>
/* 全局滚动条隐藏 */
::-webkit-scrollbar {
  width: 0 !important;
  height: 0 !important;
  background: transparent !important;
  display: none !important;
}

page {
  height: 100%;
  overflow: hidden;
  &::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
    display: none !important;
  }
}

.chat-container {
  height: 100%;
  background-color: #f0f2f5;
  overflow: hidden;

  ::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
    display: none !important;
  }
}

.chat-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.message-list {
  flex: 1;
  height: calc(100% - 140rpx);
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  position: relative;
  padding: 30rpx;
  box-sizing: border-box;
  scrollbar-width: none;
  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
    display: none !important;
    background: transparent !important;
  }
}

.message-wrapper {
  box-sizing: border-box;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  width: 100%;
  overflow: hidden;

  &::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
    display: none !important;
  }
}

.safe-area {
  height: 30rpx;
}

.message-item {
  display: flex;
  margin-bottom: 40rpx;
  align-items: flex-start;
  width: 100%;
  box-sizing: border-box;
  animation: fadeIn 0.3s ease-out;
  position: relative;

  &.message-mine {
    flex-direction: row-reverse;

    .message-content {
      margin-right: 24rpx;
      margin-left: 60rpx;
      align-items: flex-end;
    }

    .message-bubble {
      background: linear-gradient(135deg, #007aff, #00c6ff);
      color: #fff;
      border-radius: 20rpx 4rpx 20rpx 20rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.2);

      &::after {
        content: "";
        position: absolute;
        right: -12rpx;
        top: 20rpx;
        width: 0;
        height: 0;
        border-style: solid;
        border-width: 10rpx 0 10rpx 12rpx;
        border-color: transparent transparent transparent #00c6ff;
      }
    }
  }

  &:not(.message-mine) {
    .message-content {
      margin-left: 24rpx;
      margin-right: 60rpx;
    }

    .message-bubble {
      background-color: #fff;
      border-radius: 4rpx 20rpx 20rpx 20rpx;

      &::before {
        content: "";
        position: absolute;
        left: -12rpx;
        top: 20rpx;
        width: 0;
        height: 0;
        border-style: solid;
        border-width: 10rpx 12rpx 10rpx 0;
        border-color: transparent #fff transparent transparent;
      }
    }
  }
}

.avatar {
  flex-shrink: 0;
  width: 84rpx;
  height: 84rpx;
  border-radius: 42rpx;
  overflow: hidden;
  background-color: #f0f0f0;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  border: 3rpx solid #fff;
  position: relative;
  z-index: 2;

  image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.message-content {
  max-width: 60%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.message-bubble {
  position: relative;
  padding: 20rpx 24rpx;
  word-break: break-all;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  font-size: 28rpx;
  line-height: 1.5;
  min-width: 80rpx;
  box-sizing: border-box;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
  }
}

.message-time {
  font-size: 22rpx;
  color: #999;
  margin-top: 8rpx;
  text-align: center;
  opacity: 0.7;
  padding: 4rpx 12rpx;
  line-height: 1.2;
}

.msg-input-container {
  min-height: 120rpx;
  background-color: rgba(255, 255, 255, 0.98);
  border-top: 1rpx solid rgba(0, 0, 0, 0.08);
  padding: 16rpx 24rpx;
  box-sizing: border-box;
  position: relative;
  z-index: 10;
  backdrop-filter: blur(10px);
}

.msg-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  padding: 12rpx 20rpx;
  box-sizing: border-box;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.emoji-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  transition: transform 0.2s ease;
  margin-right: 8rpx;

  &:active {
    transform: scale(0.9);
  }
}

.image-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  transition: transform 0.2s ease;
  margin-right: 8rpx;

  &:active {
    transform: scale(0.9);
  }
}

.msg-input {
  flex: 1;
  height: 64rpx;
  padding: 0 16rpx;
  font-size: 28rpx;
  background-color: transparent;
}

.send-btn {
  flex-shrink: 0;
  width: 112rpx;
  height: 64rpx;
  line-height: 64rpx;
  text-align: center;
  background: linear-gradient(135deg, #007aff, #00c6ff);
  color: #fff;
  border-radius: 32rpx;
  font-size: 28rpx;
  margin-left: 16rpx;
  padding: 0;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.2);

  &:active {
    transform: scale(0.95);
    box-shadow: 0 2rpx 6rpx rgba(0, 122, 255, 0.1);
  }
}

.emoji-panel {
  position: absolute;
  bottom: 140rpx;
  left: 0;
  right: 0;
  height: 500rpx;
  background-color: rgba(255, 255, 255, 0.98);
  border-top: 1rpx solid rgba(0, 0, 0, 0.05);
  padding: 20rpx;
  box-sizing: border-box;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10px);
  animation: slideUp 0.3s ease-out;
}

.emoji-list {
  height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
    display: none !important;
  }
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 16rpx;
  padding: 16rpx;
}

.emoji-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90rpx;
  font-size: 44rpx;
  background-color: #f8f9fa;
  border-radius: 16rpx;
  cursor: pointer;
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.9);
    background-color: #e9ecef;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.image-preview {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  border-radius: 8rpx;
}
</style>
